package com.cqtczh.qhd.driver.utils;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.DecimalFormat;
import android.annotation.SuppressLint;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Environment;

/**
 * @fileName FileUtils.java
 * @package com.immomo.momo.android.util
 * @description 文件工具类
 * @author 任东卫
 * @email 86930007@qq.com
 * @version 1.0
 */
public class FileUtils {
	/**
	 * 判断SD是否可以
	 * 
	 * @return
	 */
	public static boolean isSdcardExist() {
		if (Environment.getExternalStorageState().equals(
				Environment.MEDIA_MOUNTED)) {
			return true;
		}
		return false;
	}

	/**
	 * 创建根目录
	 * 
	 * @param path
	 *            目录路径
	 */
	public static void createDirFile(String path) {
		File dir = new File(path);
		if (!dir.exists()) {
			dir.mkdirs();
		}
	}

	/**
	 * 创建文件
	 * 
	 * @param path
	 *            文件路径
	 * @return 创建的文件
	 */
	public static File createNewFile(String path) {
		File file = new File(path);
		if (!file.exists()) {
			try {
				file.createNewFile();
			} catch (IOException e) {
				return null;
			}
		}
		return file;
	}

	/**
	 * 删除文件夹
	 * 
	 * @param folderPath
	 *            文件夹的路径
	 */
	public static void delFolder(String folderPath) {
		delAllFile(folderPath);
		String filePath = folderPath;
		filePath = filePath.toString();
		java.io.File myFilePath = new java.io.File(filePath);
		myFilePath.delete();
	}

	/**
	 * 删除文件
	 * 
	 * @param path
	 *            文件的路径
	 */
	public static void delAllFile(String path) {
		File file = new File(path);
		if (!file.exists()) {
			return;
		}
		if (!file.isDirectory()) {
			return;
		}
		String[] tempList = file.list();
		File temp = null;
		for (int i = 0; i < tempList.length; i++) {
			if (path.endsWith(File.separator)) {
				temp = new File(path + tempList[i]);
			} else {
				temp = new File(path + File.separator + tempList[i]);
			}
			if (temp.isFile()) {
				temp.delete();
			}
			if (temp.isDirectory()) {
				delAllFile(path + "/" + tempList[i]);
				delFolder(path + "/" + tempList[i]);
			}
		}
	}

	/**
	 * 获取文件的Uri
	 * 
	 * @param path
	 *            文件的路径
	 * @return
	 */
	public static Uri getUriFromFile(String path) {
		File file = new File(path);
		return Uri.fromFile(file);
	}

	/**
	 * 换算文件大小
	 * 
	 * @param size
	 * @return
	 */
	public static String formatFileSize(long size) {
		DecimalFormat df = new DecimalFormat("#.00");
		String fileSizeString = "未知大小";
		if (size < 1024) {
			fileSizeString = df.format((double) size) + "B";
		} else if (size < 1048576) {
			fileSizeString = df.format((double) size / 1024) + "K";
		} else if (size < 1073741824) {
			fileSizeString = df.format((double) size / 1048576) + "M";
		} else {
			fileSizeString = df.format((double) size / 1073741824) + "G";
		}
		return fileSizeString;
	}
	
	public static File createFileInSDCard(String dirPath, String name)
			throws Exception {
		File file = new File(dirPath, name);
		file.createNewFile();
		return file;
	}
	
	public static File createFileInSDCard(String name)
	throws Exception {
		int index = name.lastIndexOf(File.separator);
		String dir = name.substring(0, index);
		creatSDDir(dir);
		return createFileInSDCard(dir, name.substring(index+1));
	}
	
	/**
	 * 创建新目录
	 */
	public static File creatSDDir(String dirPath) {
		File dirFile = new File(dirPath);
		if(!dirFile.exists()) dirFile.mkdirs();
		return dirFile;
	}
	
	/**
	 * 判断文件存不存在
	 */
	public static boolean isFileExist(String name) {
		return new File(name).exists();
	}
	
	/**
	 * 将流转化成文件，写进内存卡
	 */
	public static File write2SDFromInput(String name, InputStream input) {
		if(input == null) return null;//如果流是空的，就返回空文件
		File file = null;
		try {   
			file = createFileInSDCard(name);
			FileOutputStream output = new FileOutputStream(file);
			byte buffer[] = new byte[4 * 1024];
			int temp = -1;
			while ((temp = input.read(buffer)) != -1) {
				output.write(buffer, 0, temp);
			}
			output.flush();
			output.close();
		} catch (Exception e) {
			e.printStackTrace();
		} 
		return file;
	}
	
	public static void deleteFile(String path){
		if(path == null || "".equals(path))return;
		File file = new File(path);
		if(file.exists()){
			file.delete();
		}
	}

	public static void deleteFile(File file) {
		if (file == null || !file.exists())return;
			file.delete();
	}
	
	private static final String TAG = "FileUtil";
	/**
	 * 根据文件路径 递归创建文件
	 * 
	 * @param file
	 */
	public static void createDipPath(String file) {
		String parentFile = file.substring(0, file.lastIndexOf("/"));
		File file1 = new File(file);
		File parent = new File(parentFile);
		if (!file1.exists()) {
			parent.mkdirs();
			try {
				file1.createNewFile();
				LogUtil.i(TAG,"Create new file :" + file);
			} catch (IOException e) {
				LogUtil.e(TAG, e.getMessage());
			}
		}
	}

	/**
	 * 删除文件
	 * 
	 * @param path
	 */
	public static boolean deleteFile2(String path) {
		boolean bl;
		File file = new File(path);
		if (file.exists()) {
			bl = file.delete();
		} else {
			bl = false;
		}
		return bl;
	}
	/**
	 * 将bitmap保存到本地
	 * 
	 * @param mBitmap
	 * @param imagePath
	 */
	@SuppressLint("NewApi")
	public static void saveBitmap(Bitmap bitmap, String imagePath,int s) {
		File file = new File(imagePath);
		createDipPath(imagePath);
		FileOutputStream fOut = null;
		try {
			fOut = new FileOutputStream(file);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
		if(imagePath.toLowerCase().endsWith(".png")){
			bitmap.compress(Bitmap.CompressFormat.PNG, s, fOut);
		}else if(imagePath.toLowerCase().endsWith(".jpg")){
			bitmap.compress(Bitmap.CompressFormat.JPEG, s, fOut);
		}else{
			bitmap.compress(Bitmap.CompressFormat.WEBP, s, fOut);
		}
		try {
			fOut.flush();
		} catch (IOException e) {
			e.printStackTrace();
		}
		try {
			fOut.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	// 复制文件
		public static void copyFile(String sourcePath, String toPath) {
			File sourceFile = new File(sourcePath);
			File targetFile = new File(toPath);
			createDipPath(toPath);
			try {
				BufferedInputStream inBuff = null;
				BufferedOutputStream outBuff = null;
				try {
					// 新建文件输入流并对它进行缓冲
					inBuff = new BufferedInputStream(
							new FileInputStream(sourceFile));

					// 新建文件输出流并对它进行缓冲
					outBuff = new BufferedOutputStream(new FileOutputStream(
							targetFile));

					// 缓冲数组
					byte[] b = new byte[1024 * 5];
					int len;
					while ((len = inBuff.read(b)) != -1) {
						outBuff.write(b, 0, len);
					}
					// 刷新此缓冲的输出流
					outBuff.flush();
				} finally {
					// 关闭流
					if (inBuff != null)
						inBuff.close();
					if (outBuff != null)
						outBuff.close();
				}
			} catch (FileNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

		// 复制文件
		public static void copyFile(File sourceFile, File targetFile) {

			try {
				BufferedInputStream inBuff = null;
				BufferedOutputStream outBuff = null;
				try {
					// 新建文件输入流并对它进行缓冲
					inBuff = new BufferedInputStream(
							new FileInputStream(sourceFile));

					// 新建文件输出流并对它进行缓冲
					outBuff = new BufferedOutputStream(new FileOutputStream(
							targetFile));

					// 缓冲数组
					byte[] b = new byte[1024 * 5];
					int len;
					while ((len = inBuff.read(b)) != -1) {
						outBuff.write(b, 0, len);
					}
					// 刷新此缓冲的输出流
					outBuff.flush();
				} finally {
					// 关闭流
					if (inBuff != null)
						inBuff.close();
					if (outBuff != null)
						outBuff.close();
				}
			} catch (FileNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		
		//按质量压缩图片
		private Bitmap compressImage(Bitmap image) {

			ByteArrayOutputStream baos = new ByteArrayOutputStream();
			image.compress(Bitmap.CompressFormat.JPEG, 50, baos);//质量压缩方法，这里100表示不压缩，把压缩后的数据存放到baos中
			int options = 100;
			while ( baos.toByteArray().length / 1024>100) {	//循环判断如果压缩后图片是否大于100kb,大于继续压缩		
				baos.reset();//重置baos即清空baos
				image.compress(Bitmap.CompressFormat.JPEG, options, baos);//这里压缩options%，把压缩后的数据存放到baos中
				options -= 10;//每次都减少10
			}
			ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());//把压缩后的数据baos存放到ByteArrayInputStream中
			Bitmap bitmap = BitmapFactory.decodeStream(isBm, null, null);//把ByteArrayInputStream数据生成图片
			return bitmap;
		}

}
